package com.zs.mp.exception;

import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.zs.mp.model.ResponseResult;

import jakarta.validation.ValidationException;

@RestControllerAdvice
public class GlobalException {
	
	@ExceptionHandler(Exception.class)
	public ResponseResult<?> exception(Exception e){
	
		return ResponseResult.failure(e.getMessage());
	}
	
	@ExceptionHandler({BindException.class,ValidationException.class,MethodArgumentNotValidException.class})
	public ResponseResult<?> validationException(Exception e){
		if(e instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException manve = (MethodArgumentNotValidException)e;
			System.out.println("111111111111111111111");
			System.out.println(manve.getBindingResult().getAllErrors());
			List<ObjectError> allErrors = manve.getBindingResult().getAllErrors();
			for (ObjectError objectError : allErrors) {
				System.out.println(objectError.getDefaultMessage());
			}
			String err = manve.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";"));
			return ResponseResult.failure(err);
		}
		return ResponseResult.failure(null);
	}
	
}
